import axios from 'axios'
import { BaseService } from './BaseService'
import { Base64 } from 'js-base64'

export class PublicService extends BaseService {
    // get
    // 获取推荐页面
    public async getRecommends(p: number, n: number) {
        const url = this.communityBaseUrl + '/recommends?p=' + p + '&n=' + n
        axios
            .get(url)
            .then(res => {
                this.success()
            })
            .catch(err => {
                this.failed(err)
            })
        return await axios.get(url)
    }

    // post
    // 注册、登录
    // type： join | login
    public async login(date: any) {
        const url = this.communityBaseUrl + '/login'
        await axios
            .post(url, date)
            .then(res => {
                const data = {
                    account: date.account,
                    // data: res.data.data
                    id: Base64.decode(res.data.data.split('.')[1]).split('"')[7],
                    data: res.data.data
                }
                localStorage.setItem('account', JSON.stringify(data))
                window.location.pathname = '/editorial'
            })
            .catch(err => {
                err.message == 'Request failed with status code 401'
                    ? alert('登陆失败，用户名或密码错误')
                    : alert('登陆失败，用户不存在')
            })
    }

    public async join(date: any) {
        const url = this.communityBaseUrl + '/join'
        await axios
            .post(url, date)
            .then(res => {
                alert('注册成功。')
                window.location.pathname = '/account/login'
            })
            .catch(err => {
                if (err.message == 'Request failed with status code 409') alert('账号已存在')
            })
    }
}
